<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品图片放大镜</title>
    <style>
        /* 图片容器 */
        .image-container {
            position: relative;
            width: 400px;
            overflow: hidden;
        }

        /* 原始图片 */
        .original-image {
            display: block;
            width: 100%;
            cursor: zoom-in;
        }

        /* 放大后的图片 */
        .zoomed-image {
            display: none;
            position: absolute;
            z-index: 999;
            cursor: zoom-out;
        }
    </style>
</head>

<body>
    <div class="image-container">
        <img src="https://image.brilliantearth.com/media/carat_image/7B/BE1D13065_MQ_100ct_yellow_side1.jpg"
            class="original-image" alt="商品图片">
        <img src="https://image.brilliantearth.com/media/carat_image/7B/BE1D13065_MQ_100ct_yellow_side1.jpg"
            class="zoomed-image" alt="放大后的商品图片">
    </div>

    <script>
        var imageContainer = document.querySelector('.image-container');
        var originalImage = document.querySelector('.original-image');
        var zoomedImage = document.querySelector('.zoomed-image');
        originalImage.addEventListener('click', function (e) {
            zoomedImage.style.display = 'block';
            var rect = imageContainer.getBoundingClientRect();
            var scaleX = zoomedImage.width / originalImage.width;
            var scaleY = zoomedImage.height / originalImage.height;
            var offsetX = (e.clientX - rect.left) * scaleX - (e.clientX - rect.left);
            var offsetY = (e.clientY - rect.top) * scaleY - (e.clientY - rect.top);
            // 设置放大图片的位置，修复偏移量
            zoomedImage.style.left = -offsetX + 'px';
            zoomedImage.style.top = -offsetY + 'px';
            // 在鼠标移动时更新放大图片的位置
            imageContainer.addEventListener('mousemove', moveZoomedImage);
        });
        function moveZoomedImage(e) {
            var rect = imageContainer.getBoundingClientRect();
            var scaleX = zoomedImage.width / originalImage.width;
            var scaleY = zoomedImage.height / originalImage.height;
            var offsetX = (e.clientX - rect.left) * scaleX - (e.clientX - rect.left);
            var offsetY = (e.clientY - rect.top) * scaleY - (e.clientY - rect.top);
            // 图片的位置反向移动
            zoomedImage.style.left = -offsetX + 'px';
            zoomedImage.style.top = -offsetY + 'px';
        }
        zoomedImage.addEventListener('click', function () {
            zoomedImage.style.display = 'none';
            imageContainer.removeEventListener('mousemove', moveZoomedImage);
        });
        imageContainer.addEventListener('mouseleave', function () {
            zoomedImage.style.display = 'none';
            imageContainer.removeEventListener('mousemove', moveZoomedImage);
        });
    </script>
</body>

</html>